<template>
  <div class="department-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">第一步: 选择科室</div>
        <div class="home-btn">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 科室标题和操作按钮 -->
    <div class="section-header">
      <div class="title-section">
        <div class="main-title">科室</div>
        <div class="sub-title">找到您想要的科室</div>
      </div>
      <div class="action-buttons">
        <div class="action-btn" @click="goToSearch">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="11" cy="11" r="8"/>
            <path d="m21 21-4.35-4.35"/>
          </svg>
        </div>
        <div class="action-btn">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="8" y1="6" x2="21" y2="6"/>
            <line x1="8" y1="12" x2="21" y2="12"/>
            <line x1="8" y1="18" x2="21" y2="18"/>
            <line x1="3" y1="6" x2="3.01" y2="6"/>
            <line x1="3" y1="12" x2="3.01" y2="12"/>
            <line x1="3" y1="18" x2="3.01" y2="18"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 科室列表 -->
    <div class="department-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在加载科室数据...</div>
      </div>
      
      <!-- 错误提示 -->
      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ error }}</div>
        <button class="retry-btn" @click="fetchDepartments">重试</button>
      </div>
      
      <!-- 科室列表 -->
      <div v-else>
        <div 
          class="department-card" 
          :class="{ 'selected': selectedDepartmentId === dept._id }"
          v-for="dept in departments" 
          :key="dept._id"
          @click="selectDepartment(dept)"
        >
          <DepartmentIcon 
            :department-name="dept.name" 
            :icon-url="dept.icon"
          />
          <div class="dept-info">
            <div class="dept-name">{{ dept.name }}</div>
            <div class="hospital-count">{{ dept.hospitalCount }} 医院</div>
            <div class="price-range">¥{{ dept.priceRange }}</div>
            <div class="next-time">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12,6 12,12 16,14"/>
              </svg>
              <span class="time-label">下一个可用时间</span>
              <span class="time-value">{{ dept.nextTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <button 
        v-if="selectedDepartmentId" 
        class="clear-btn" 
        @click="clearSelection"
      >
        清除选择
      </button>
      <button 
        class="next-btn" 
        :class="{ 'disabled': !selectedDepartmentId }"
        @click="goToNextStep"
      >
        下一步
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import DepartmentIcon from '../../components/DepartmentIcon.vue'

const router = useRouter()

const departments = ref<any[]>([])
const loading = ref(false)
const error = ref('')
const selectedDepartmentId = ref<string>('')

const fetchDepartments = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 直接使用axios发送请求
    const response = await axios.get('http://localhost:3000/sow/departments')
    console.log('API响应:', response.data)
    console.log('API响应类型:', typeof response.data)
    console.log('API响应数据结构:', Object.keys(response.data))
    
    // 尝试不同的数据结构
    let data = []
    if (response.data && response.data.data) {
      data = response.data.data
    } else if (Array.isArray(response.data)) {
      data = response.data
    } else if (response.data && Array.isArray(response.data.departments)) {
      data = response.data.departments
    } else {
      console.log('API返回的数据结构不符合预期，使用默认数据')
      throw new Error('数据结构不符合预期')
    }
    
    departments.value = data
    console.log('处理后的科室数据:', departments.value)
    console.log('科室数据长度:', departments.value.length)
    
  } catch (err) {
    console.error('获取科室数据失败:', err)
    error.value = '获取科室数据失败，请稍后重试'
    
    // 如果API调用失败，使用默认数据
    console.log('使用默认科室数据')
    departments.value = [
      {
        _id: '1',
        name: '一般护理',
        description: '提供基础护理服务',
        hospitalCount: 47,
        priceRange: '50-100',
        nextTime: '12月23日 上午08:30',
        icon: 'https://img.icons8.com/color/48/000000/doctor-male.png',
        status: 'active',
        sortOrder: 1
      },
      {
        _id: '2',
        name: '儿科',
        description: '专门为儿童提供医疗服务',
        hospitalCount: 24,
        priceRange: '80-150',
        nextTime: '12月23日 下午14:00',
        icon: 'https://img.icons8.com/color/48/000000/baby.png',
        status: 'active',
        sortOrder: 2
      },
      {
        _id: '3',
        name: '心脏病学科室',
        description: '心脏疾病诊断和治疗',
        hospitalCount: 58,
        priceRange: '120-200',
        nextTime: '12月24日 上午09:00',
        icon: 'https://img.icons8.com/color/48/000000/heart-with-pulse.png',
        status: 'active',
        sortOrder: 3
      },
      {
        _id: '4',
        name: '心脏病学科室',
        description: '心脏疾病诊断和治疗',
        hospitalCount: 508,
        priceRange: '150-300',
        nextTime: '12月24日 下午15:30',
        icon: 'https://img.icons8.com/color/48/000000/heart-with-pulse.png',
        status: 'active',
        sortOrder: 4
      },
      {
        _id: '5',
        name: '耳鼻喉科',
        description: '耳鼻喉疾病诊断和治疗',
        hospitalCount: 508,
        priceRange: '50-100',
        nextTime: '12月23日 上午08:30',
        icon: 'https://img.icons8.com/color/48/000000/stethoscope.png',
        status: 'active',
        sortOrder: 5
      },
      {
        _id: '6',
        name: '卫生保健科',
        description: '健康检查和预防保健',
        hospitalCount: 508,
        priceRange: '50-100',
        nextTime: '12月23日 上午08:30',
        icon: 'https://img.icons8.com/color/48/000000/health-graph.png',
        status: 'active',
        sortOrder: 6
      }
    ]
  } finally {
    loading.value = false
    console.log('fetchDepartments完成，最终科室数据:', departments.value)
    console.log('科室数据长度:', departments.value.length)
  }
}

onMounted(() => {
  fetchDepartments()
  // 从本地存储恢复选中状态
  const savedDepartmentId = localStorage.getItem('selectedDepartmentId')
  if (savedDepartmentId) {
    selectedDepartmentId.value = savedDepartmentId
  }
})

const selectDepartment = (dept: any) => {
  console.log('选择科室:', dept.name)
  
  // 更新选中状态
  selectedDepartmentId.value = dept._id
  
  // 存储选中的科室ID到本地存储
  localStorage.setItem('selectedDepartmentId', dept._id)
  
  // 存储选中的科室完整信息到本地存储
  localStorage.setItem('selectedDepartment', JSON.stringify(dept))
  
  // 不立即跳转，让用户看到选中效果
  // 用户需要点击"下一步"按钮才会跳转
}

const goToNextStep = () => {
  console.log('点击下一步')
  // 检查是否有选中的科室
  if (selectedDepartmentId.value) {
    router.push('/hospital-select')
  } else {
    // 使用轻提示
    showToast('请先选择一个科室')
  }
}

// 轻提示函数
const showToast = (message: string) => {
  // 创建toast元素
  const toast = document.createElement('div')
  toast.className = 'toast-message'
  toast.textContent = message
  
  // 添加到页面
  document.body.appendChild(toast)
  
  // 显示动画
  setTimeout(() => {
    toast.classList.add('show')
  }, 10)
  
  // 3秒后移除
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      document.body.removeChild(toast)
    }, 300)
  }, 3000)
}

// 清除选中状态
const clearSelection = () => {
  selectedDepartmentId.value = ''
  localStorage.removeItem('selectedDepartmentId')
  localStorage.removeItem('selectedDepartment')
  console.log('已清除选中状态')
}

const goToSearch = () => {
  console.log('点击搜索按钮')
  router.push('/department-search')
}


</script>

<style lang="scss" scoped>
.department-page {
  min-height: 100vh;
  background: #f6f8fc;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  background: #1877F2;
  padding: 12px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 44px;
}

.back-btn, .home-btn {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.section-header {
  background: #fff;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border-bottom: 1px solid #f0f0f0;
}

.title-section {
  .main-title {
    font-size: 24px;
    font-weight: 700;
    color: #222;
    margin-bottom: 4px;
  }
  .sub-title {
    font-size: 14px;
    color: #666;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fff;
}

.department-list {
  padding: 16px;
  padding-bottom: 100px; // 为底部按钮留出空间
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1877F2;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  margin-bottom: 10px;
}

.error-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.error-text {
  margin-bottom: 15px;
  text-align: center;
}

.retry-btn {
  width: 100px;
  height: 40px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background: #1565c0;
  }
  
  &:active {
    background: #0d47a1;
  }
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.bottom-button {
  display: flex;
  gap: 12px;
  align-items: center;
}

.clear-btn {
  height: 48px;
  padding: 0 20px;
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: #e0e0e0;
    color: #333;
  }
  
  &:active {
    background: #d0d0d0;
  }
}

.next-btn {
  flex: 1;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: #1565c0;
  }
  
  &:active {
    background: #0d47a1;
  }
  
  &.disabled {
    background: #ccc;
    color: #999;
    cursor: not-allowed;
    
    &:hover {
      background: #ccc;
    }
  }
}

.department-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(24,119,242,0.15);
  }
  
  &.selected {
    border-color: #1877F2;
    background: linear-gradient(135deg, #f8fbff 0%, #e3f2fd 100%);
    box-shadow: 0 4px 16px rgba(24,119,242,0.2);
    transform: translateY(-2px);
    
    .dept-name {
      color: #1877F2;
      font-weight: 700;
    }
    
    .price-range {
      color: #1877F2;
      font-weight: 600;
    }
    
    .time-value {
      color: #1877F2;
      font-weight: 600;
    }
  }
}



.dept-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.dept-name {
  font-size: 16px;
  font-weight: 600;
  color: #222;
}

.hospital-count {
  font-size: 14px;
  color: #666;
}

.price-range {
  font-size: 14px;
  color: #ff6b35;
  font-weight: 500;
}

.next-time {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
  
  .time-label {
    flex: 1;
  }
  
  .time-value {
    color: #1877F2;
    font-weight: 500;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 轻提示样式
.toast-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.8);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 9999;
  opacity: 0;
  transition: all 0.3s ease;
  pointer-events: none;
  
  &.show {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}
</style> 